package core.tool.scan;

import java.io.File;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import core.tool.common.SystemInfo;

public class ScanService {
	
	public List<Object> annotationList=null;
	
	
	public void scanPackage(String packagePath,Class annotationClass) {
		annotationList=new ArrayList<Object>();
		String allClasssPath=SystemInfo.ROOT_PATH+"/WEB-INF/classes";
		String folder=allClasssPath+"\\"+packagePath.replace(".", "\\");
		File folderFile=new File(folder);		
		handlerDirectory(folderFile,packagePath,annotationClass);
	}	

	private  void handlerDirectory(File folderFile,String packagePath,Class annotationClass) {
		try {
			File[] files = folderFile.listFiles();
			for (File file : files) {
				if (file.isDirectory()) {
					handlerDirectory(file, packagePath,annotationClass);
				} else if (file.isFile()) {
					String absolutePath = file.getAbsolutePath();
					if (!absolutePath.endsWith(".class"))continue;
					int begin = absolutePath.indexOf(packagePath.replace(".", "\\"));
					int end = absolutePath.lastIndexOf(".");
					String thisClassPath = absolutePath.substring(begin, end).replace("\\", ".");
					Class cla = Class.forName(thisClassPath);
					scanAnnotationForRequestMapping(cla,annotationClass);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private  void  scanAnnotationForRequestMapping(Class cla,Class annotationClass) throws InstantiationException, IllegalAccessException {
		Annotation[] classAnnotations=cla.getAnnotations();		
		for(Annotation annotation : classAnnotations) {
			if(annotation.annotationType()==annotationClass) {
				annotationList.add(cla.newInstance());
			}
		}		
	}
	
	
}
